package com.lingyue.commons.response;

import com.lingyue.commons.exceptions.CommException;
import com.lingyue.commons.exceptions.CommRuntimeException;
import com.lingyue.commons.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;

/**
 * @version 1.0.0
 * @author: lzy
 * @date: 2019/11/25 16:17
 */
@Slf4j
@RestControllerAdvice
public class CommExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResEntity handleException(MethodArgumentNotValidException e, HttpServletResponse response) {
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        log.error(ExceptionUtils.getRootCauseMessage(e));
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return ResEntity.fail(e.getBindingResult());
    }

    @ExceptionHandler(CommException.class)
    public ResEntity handleException(CommException e, HttpServletResponse response) {
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        log.error(ExceptionUtils.getRootCauseMessage(e));
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return ResEntity.fail(e);
    }

    @ExceptionHandler(CommRuntimeException.class)
    public ResEntity handleException(CommRuntimeException e, HttpServletResponse response) {
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        log.error(ExceptionUtils.getRootCauseMessage(e));
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return ResEntity.fail(e);
    }

    @ExceptionHandler(SQLException.class)
    public ResEntity handleException(SQLException e, HttpServletResponse response) {
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        log.error(ExceptionUtils.getRootCauseMessage(e));
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return ResEntity.fail(50000, "数据库错误" + ExceptionUtils.getRootCauseMessage(e));
    }

    @ExceptionHandler(Exception.class)
    public ResEntity handleException(Exception e, HttpServletResponse response) {
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        log.error(ExceptionUtils.getRootCauseMessage(e));
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return ResEntity.fail(50000, ExceptionUtils.getRootCauseMessage(e));
    }

}
